/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CourseClassMaterialPanel.java
 *
 * Created on Apr 18, 2009, 4:16:41 PM
 */
package br.unisc.pdaapp.ui;

import br.unisc.pdaapp.constants.IPanels;
import br.unisc.pdaapp.meta.IForm;
import br.unisc.pdaapp.meta.Material;
import br.unisc.pdaapp.webservice.client.WSHandler;
import br.unisc.pdaapp.xml.MoodleXmlReader;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import sun.misc.BASE64Decoder;

/**
 *
 * @author guilherme
 */
public class MaterialPanel extends javax.swing.JPanel implements IForm
{

    private static MaterialPanel instance;

    private int courseSectionID = -1;

    /** Creates new form CourseClassMaterialPanel */
    private MaterialPanel()
    {
        initComponents();
    }

    public static MaterialPanel getInstance()
    {
        if (instance == null)
        {
            instance = new MaterialPanel();
        }

        return instance;
    }

    public void setUploadButtonVisible(boolean state)
    {
        uploadButton.setVisible(state);
    }

    public void setHeader(String text)
    {
        welcomeLabel.setText(text);
    }

    public int getCourseSectionID()
    {
        return courseSectionID;
    }

    public void loadMaterialBy(final int courseID, final int courseSectionID)
    {
        this.courseSectionID = courseSectionID;
        
        centerPanel.removeAll();

        try
        {
            final WSHandler wsHandler = new WSHandler();

            byte[] result = wsHandler.getMaterial(courseID, courseSectionID);

            BASE64Decoder based = new BASE64Decoder();

            String encoded = new String(result);
            byte[] decoded = based.decodeBuffer(encoded);
            String xml = new String(decoded);
            System.out.println("xml: " + xml);

            MoodleXmlReader moodleXmlReader = new MoodleXmlReader();
            moodleXmlReader.readXML(xml, MoodleXmlReader.MATERIAL, decoded);
            Vector classes = moodleXmlReader.getResultData();

            JLabel classLabel = null;
            JButton downloadButton = null;
            GridBagConstraints visibleGridBagConstraints = null;
            GridBagConstraints labelGridBagConstraints = null;
            GridBagConstraints buttonGridBagConstraints = null;

            final Icon hideIcon = new javax.swing.ImageIcon(getClass().getResource("/br/unisc/pdaapp/ui/images/hide.gif"));
            final Icon showIcon = new javax.swing.ImageIcon(getClass().getResource("/br/unisc/pdaapp/ui/images/show.gif"));

            boolean student = MoodleMobileFrame.getInstance().isStudent();

            int visibleMaterialsCount = student ? 0 : classes.size();
            for (int x = 0; x < classes.size(); x++)
            {
                final Material material = (Material) classes.get(x);

                if (material.isVisible() && student)
                {
                    visibleMaterialsCount++;
                }
            }

            int x=0;
            for (int y = 0; y < classes.size(); y++)
            {
                final Material material = (Material) classes.get(y);

                //se a aula não estiver visivel e for um aluno então não a mostra.
                if (!material.isVisible() && student)
                {
                    continue;
                }

                visibleGridBagConstraints = new GridBagConstraints();
                visibleGridBagConstraints.weightx = 0;
                visibleGridBagConstraints.weighty = ((x == visibleMaterialsCount - 1) ? 1 : 0);
                visibleGridBagConstraints.gridx = 0;
                visibleGridBagConstraints.gridy = x;
                visibleGridBagConstraints.anchor = GridBagConstraints.NORTHWEST;
                visibleGridBagConstraints.insets = new Insets(3, 2, 0, 2);

                final JButton visibleButton = new JButton();
                visibleButton.setContentAreaFilled(false);
                visibleButton.setBorder(null);

                if (!student)
                {
                    visibleButton.setIcon(material.isVisible() ? hideIcon : showIcon);
                    visibleButton.addActionListener(new ActionListener()
                    {

                        public void actionPerformed(ActionEvent e)
                        {
                            int result = wsHandler.updateMaterialVisibility(material.getId(), courseID, courseSectionID, material.getModuleID(), !material.isVisible());

                            if (result != -1)
                            {
                                material.setVisible(!material.isVisible());
                                visibleButton.setIcon(material.isVisible() ? hideIcon : showIcon);
                            }
                        }
                    });
                    centerPanel.add(visibleButton, visibleGridBagConstraints);
                }
                else
                {
                    centerPanel.add(new JLabel(), visibleGridBagConstraints);
                }

                labelGridBagConstraints = new GridBagConstraints();
                labelGridBagConstraints.weightx = 1;
                labelGridBagConstraints.weighty = ((x == visibleMaterialsCount - 1) ? 1 : 0);
                labelGridBagConstraints.gridx = 2;
                labelGridBagConstraints.gridy = x;
                labelGridBagConstraints.anchor = GridBagConstraints.NORTHWEST;
                labelGridBagConstraints.insets = new Insets(3, 0, 0, 2);

                classLabel = new JLabel(material.getName());
                classLabel.setFont(new java.awt.Font("Tahoma", 0, 10));

                //adiciona label com descrição da aula.
                centerPanel.add(classLabel, labelGridBagConstraints);

                buttonGridBagConstraints = new GridBagConstraints();
                buttonGridBagConstraints.weightx = 0;
                buttonGridBagConstraints.weighty = ((x == visibleMaterialsCount - 1) ? 1 : 0);
                buttonGridBagConstraints.gridx = 1;
                buttonGridBagConstraints.gridy = x;
                buttonGridBagConstraints.anchor = GridBagConstraints.NORTHEAST;
                buttonGridBagConstraints.insets = new Insets(0, 2, 0, 2);

                downloadButton = new JButton();
                downloadButton.setContentAreaFilled(false);
                downloadButton.setFont(new java.awt.Font("Tahoma", 0, 10));
                downloadButton.setBorder(null);

                if (material.getDesc().indexOf("http:") != -1 || material.getModuleID() == 9)
                {
                    classLabel.setText(classLabel.getText() + " - " + material.getDesc());
                }
                else
                {
                    downloadButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unisc/pdaapp/ui/images/download.jpeg")));
                    downloadButton.addActionListener(new ActionListener()
                    {

                        public void actionPerformed(ActionEvent e)
                        {
                            messageLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unisc/pdaapp/ui/images/loading.gif")));
                            messageLabel.setText("Baixando arquivo...");
                            messageLabel.repaint();
                            try
                            {
                                Thread.sleep(1000);
                            }
                            catch (InterruptedException ex)
                            {
                                ex.printStackTrace();
                            }

                            byte[] file = wsHandler.downloadMaterial(courseID, material.getDesc());
                            saveMaterialToFile(file, material.getDesc());
                        }
                    });
                }

                centerPanel.add(downloadButton, buttonGridBagConstraints);
                x++;
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    private void saveMaterialToFile(byte[] fileByte, String fileName)
    {
        messageLabel.setText("Salvando arquivo...");
        File file = new File(fileName);
        try
        {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(fileByte);
            fileOutputStream.close();

            messageLabel.setText("Arquivo baixado!");
            messageLabel.setIcon(null);
        }
        catch (FileNotFoundException ex)
        {
            ex.printStackTrace();
            messageLabel.setText("Erro ao baixar!");
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
            messageLabel.setText("Erro ao baixar!");
        }
    }

    public JLabel getMessageLabel()
    {
        return messageLabel;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        northPanel = new javax.swing.JPanel();
        welcomeLabel = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        backButton1 = new javax.swing.JButton();
        uploadButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();
        messageLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        centerPanel = new javax.swing.JPanel();

        setBackground(new java.awt.Color(255, 255, 255));
        setLayout(new java.awt.BorderLayout());

        northPanel.setOpaque(false);
        northPanel.setLayout(new java.awt.GridBagLayout());

        welcomeLabel.setText("jLabel1");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 2, 4, 2);
        northPanel.add(welcomeLabel, gridBagConstraints);

        jPanel1.setOpaque(false);
        jPanel1.setLayout(new java.awt.GridBagLayout());

        backButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unisc/pdaapp/ui/images/back.jpeg"))); // NOI18N
        backButton1.setBorder(null);
        backButton1.setOpaque(false);
        backButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButton1ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 1);
        jPanel1.add(backButton1, gridBagConstraints);

        uploadButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unisc/pdaapp/ui/images/upload.jpg"))); // NOI18N
        uploadButton.setBorder(null);
        uploadButton.setOpaque(false);
        uploadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uploadButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 1);
        jPanel1.add(uploadButton, gridBagConstraints);

        exitButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unisc/pdaapp/ui/images/close.jpeg"))); // NOI18N
        exitButton.setBorder(null);
        exitButton.setOpaque(false);
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        jPanel1.add(exitButton, gridBagConstraints);

        messageLabel.setFont(new java.awt.Font("Tahoma", 0, 10));
        messageLabel.setForeground(new java.awt.Color(153, 153, 153));
        messageLabel.setText(" ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 2, 4, 2);
        jPanel1.add(messageLabel, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        northPanel.add(jPanel1, gridBagConstraints);

        add(northPanel, java.awt.BorderLayout.NORTH);

        centerPanel.setBackground(new java.awt.Color(255, 255, 255));
        centerPanel.setLayout(new java.awt.GridBagLayout());
        jScrollPane1.setViewportView(centerPanel);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void backButton1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_backButton1ActionPerformed
    {//GEN-HEADEREND:event_backButton1ActionPerformed
        messageLabel.setText(" ");
        MoodleMobileFrame.getInstance().switchPanel(IPanels.CLASSES_PANE);
}//GEN-LAST:event_backButton1ActionPerformed

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_exitButtonActionPerformed
    {//GEN-HEADEREND:event_exitButtonActionPerformed
        messageLabel.setText(" ");
        MoodleMobileFrame.getInstance().quit(this);
}//GEN-LAST:event_exitButtonActionPerformed

    private void uploadButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_uploadButtonActionPerformed
    {//GEN-HEADEREND:event_uploadButtonActionPerformed
        MoodleMobileFrame.getInstance().switchPanel(IPanels.UPLOAD_PANE);
        File file = new File(System.getProperty("user.home"));
        UploadPanel.getInstance().listFiles(file);
}//GEN-LAST:event_uploadButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton backButton1;
    private javax.swing.JPanel centerPanel;
    private javax.swing.JButton exitButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel messageLabel;
    private javax.swing.JPanel northPanel;
    private javax.swing.JButton uploadButton;
    private javax.swing.JLabel welcomeLabel;
    // End of variables declaration//GEN-END:variables
}
